<template>
  <view class="home" :style="{ paddingTop: `${statusBarHeight * 2}rpx`, overflow: getOverflow }">
    <view class="home-user" :style="{ height: `${navigatorHeight * 2}rpx` }" @click="() => { if (studentList.length > 1) showChangeUser = true }">
      <view class="info-name">
        {{ userStore.userName }}
      </view>
      <image v-if="studentList.length > 1" class="icon-down" src="https://cbandu.oss-cn-qingdao.aliyuncs.com/imgs/20250709/icon_down.png" />
    </view>

    <view class="home-main">
      <view class="home-swiper">
        <swiper class="swiper" circular :indicator-dots="false" :autoplay="true">
          <swiper-item v-for="(item, index) in swiperList" :key="`img${index}`">
            <image class="swiper-item" :src="item" mode="aspectFill" />
          </swiper-item>
        </swiper>
      </view>

      <view class="home-ghost">
        <view class="ghost-item" @click="toDetail('baike')">
          <image class="ghost-img" src="https://cbandu.oss-cn-qingdao.aliyuncs.com/imgs/20250902/baike.png" mode="aspectFill" />
          <text class="ghost-text">
            百科
          </text>
        </view>
        <view class="ghost-item" @click="toDetail('gushi')">
          <image class="ghost-img" src="https://cbandu.oss-cn-qingdao.aliyuncs.com/imgs/20250902/gushi.png" mode="aspectFill" />
          <text class="ghost-text">
            故事
          </text>
        </view>
        <view class="ghost-item" @click="toDetail('yuedu')">
          <image class="ghost-img" src="https://cbandu.oss-cn-qingdao.aliyuncs.com/imgs/20250902/yuedu.png" mode="aspectFill" />
          <text class="ghost-text">
            阅读
          </text>
        </view>
      </view>

      <image v-if="!loginFlag" class="home-signIn" src="https://cbandu.oss-cn-qingdao.aliyuncs.com/yusj/20250516/denglu.png" @click="toLogin" />
      <image v-else class="home-signIn" src="https://cbandu.oss-cn-qingdao.aliyuncs.com/yusj/20250516/qiandao.png" @click="toSignIn" />

      <view class="home-course">
        <view class="course-item" @click="toAnswer">
          <image class="item-bg" src="https://cbandu.oss-cn-qingdao.aliyuncs.com/yusj/20250526/yuedu_bg.png" />
          <view class="item-title">
            读后自测
          </view>
          <view class="item-desc">
            阅读小达人，打卡向前冲
          </view>
          <image class="item-icon" src="https://cbandu.oss-cn-qingdao.aliyuncs.com/yusj/20250516/yuedu.png" />
        </view>
        <view class="course-item" @click="toWsClassroom">
          <image class="item-bg" src="https://cbandu.oss-cn-qingdao.aliyuncs.com/yusj/20250526/wushang_bg.png" />
          <view class="item-title">
            五商课堂
          </view>
          <view class="item-desc">
            快乐学五商，成长不打烊
          </view>
          <image class="item-icon item-icon-right" src="https://cbandu.oss-cn-qingdao.aliyuncs.com/yusj/20250516/wushang.png" />
        </view>
      </view>

      <view class="home-read">
        <view class="read-title">
          <text class="title-text">
            正在读书
          </text>
          <view class="title-more" @click="toCurriculum">
            <text class="more-text">
              查看课表
            </text>
            <image class="more-icon" src="https://cbandu.oss-cn-qingdao.aliyuncs.com/yusj/20250516/icon_more.png" />
          </view>
        </view>

        <view class="read-list">
          <view v-for="item in readList" :key="item.id" :data="item" class="content">
            <ReadItem :data="item" />
          </view>

          <view v-if="!readList?.length || !loginFlag" class="no-data">
            <template v-if="!loginFlag">
              <text class="no-data-text no-data-text-login">
                暂未登录，立即登录开启阅读之旅吧
              </text>
              <view class="no-data-btn" @click="toLogin">
                登录
              </view>
            </template>
            <template v-else>
              <image class="no-data-img" src="https://cbandu.oss-cn-qingdao.aliyuncs.com/imgs/20250902/img.png" />
              <text class="no-data-text">
                {{ userStore.vip.flag === 0 ? 'VIP未开通，无法查看正在读的书请联系门店老师免费开通VIP吧' : userStore.vip.flag === 3 ? 'VIP未生效，无法查看正在读的书' : '暂无正在读的书，先去看看其他内容吧' }}
              </text>
            </template>
          </view>
        </view>
      </view>
    </view>
  </view>

  <BgOverlay v-model:show="showSign" :detail="signDetail" @handle-sign="handleSign" />
  <IpOverlay v-model:show="showSuccess" :number="signNumber" :info="signInfo" />
  <ContactTeacher v-model:show-overlay="showTeacher" :type="teacherType" />
  <LoginOverlay v-model:show="showLogin" />
  <VipOverlay v-model:show="showVip" :type="vipType" :date="vipDate" :price="vipPrice" @close="handleCloseVip" />
  <ChangeUser v-model:show="showChangeUser" :user-list="studentList" @change-user="getData" />
</template>

<script setup lang="ts">
import { useUserStore } from '@/store';
import { getEntryType, getStudentList, isLogin } from '@/utils/auth';
import { getBannerList, getReadingBook, getTodaySignStatus } from '@/api/home';
import type { GetTodaySignStatusResult, ReadingBookResult } from '@/api/home/type';
import { doSign } from '@/api/sign/index';
import type { DoSignResult } from '@/api/sign/type';
import { getUserTrustClass } from '@/api/wsClassroom';
import { getSignInfo, setNavigationHeight, setSignInfo } from '@/utils/auth/index';
import { formatSimpleDate } from '@/utils/common';

const userStore = useUserStore();
const loginFlag = ref<boolean>(isLogin());
const hasSchool = computed(() => !!userStore.schoolId); // 是否绑定门店
const studentList = ref<Array<any>>(getStudentList());

const swiperList = ref<Array<string>>([]);

const signStatus = ref<string>(''); // 签到状态 1-已签到 0-未签到
const isTrustClass = ref<number>(0); // 是否报名五商课堂 1-已报名 0-未报名
const teacherType = ref<number>(1); // 1-阅读 2-托管
// 显示签到
const showSign = ref<boolean>(false);
const signDetail = ref<GetTodaySignStatusResult>();
let firstEnter: boolean = true;
const entryType = getEntryType();
const showVip = ref<boolean>(false);
const vipType = ref<number>(1);
const vipDate = ref<string>(userStore.vip.duration);
const vipPrice = ref<string>(userStore.vip.monthMoney);
const showLogin = ref<boolean>(false);
const showChangeUser = ref<boolean>(false);
const readList = ref<ReadingBookResult>();
// 显示签到
const handleShowSign = () => {
  const signData = JSON.parse(getSignInfo() || '{}');
  if (!showVip.value && (!signData?.signDay || signData.signDay !== signDetail.value!.today)) {
    showSign.value = true;
    const data = {
      ...signData,
      signDay: signDetail.value!.today,
    };
    setSignInfo(JSON.stringify(data));
  }
};
const handleCloseVip = () => { // 关闭会员弹窗后需判断是否显示签到弹窗
  handleShowSign();
};
const getData = async () => {
  if (loginFlag.value) {
    await userStore.getStudentList();
    studentList.value = getStudentList();

    if (entryType === 'scan') { // 扫码进入首页
      if (firstEnter && userStore.schoolId) { // 首次进入且挂载门店
        vipType.value = userStore.vip.flag === 2 ? 2 : userStore.vip.flag === 1 ? 1 : 3;
        showVip.value = true;
        firstEnter = false;
      }
    }
    else { // 搜索首次进入首页
      if (userStore.vip.flag !== 1 && userStore.schoolId) { // 当前不是vip且挂载门店
        const vipData = JSON.parse(getSignInfo() || '{}');
        if (!vipData?.vipDay || vipData.vipDay !== formatSimpleDate(new Date())) { // 今天还未显示vip弹窗
          vipType.value = userStore.vip.flag === 0 ? 0 : userStore.vip.flag === 2 ? 2 : 7;
          showVip.value = true;
          const data = {
            ...vipData,
            vipDay: formatSimpleDate(new Date()),
          };
          setSignInfo(JSON.stringify(data));
        }
      }
    }

    getTodaySignStatus().then((res: GetTodaySignStatusResult) => {
      signDetail.value = res;
      signStatus.value = res.status;
      userStore.setSignStatus(res.status);
      if (signStatus.value === '0') // 未签到
        handleShowSign();
    });

    getUserTrustClass().then((res: { flag: number }) => {
      isTrustClass.value = res.flag;
    });

    getReadingBook().then((res: ReadingBookResult) => {
      readList.value = res.classCourseList;
    });
  }

  getBannerList().then((res: any) => {
    swiperList.value = res.rows?.map((item: any) => {
      return item.fileUrl;
    }) || [];
  });
};

onShow(async () => {
  if (loginFlag.value) {
    await userStore.info();
  }
  getData();
});

// 去签到
const toSignIn = () => {
  uni.navigateTo({
    url: '/pages/views/signIn/index',
  });
};

// 去课表
const toCurriculum = () => {
  uni.switchTab({
    url: '/pages/tab/curriculum/index',
  });
};

const toDetail = (type: string) => {
  if (type === 'baike') {
    uni.navigateTo({
      url: '/pages/views/baike/index',
    });
  }
  else if (type === 'gushi') {
    uni.navigateTo({
      url: '/pages/views/gushi/index',
    });
  }
  else if (type === 'yuedu') {
    uni.navigateTo({
      url: '/pages/views/yuedu/index',
    });
  }
};

const showTeacher = ref<boolean>(false);
// 去阅读测验 1.未登录-toast 2.未绑定门店-老师弹窗 3.vip过期-vip弹窗 4.无数据-toast
const toAnswer = () => {
  if (!loginFlag.value) { // 未登录
    showLogin.value = true;
    return;
  }

  if (!hasSchool.value) { // 未绑定门店
    teacherType.value = 1;
    showTeacher.value = true;
    return;
  }

  uni.switchTab({
    url: '/pages/tab/curriculum/index',
  });
};

// 去五商课堂
const toWsClassroom = () => {
  if (!loginFlag.value) { // 未登录
    showLogin.value = true;
    return;
  }

  if (!hasSchool.value) { // 未绑定门店
    teacherType.value = 2;
    showTeacher.value = true;
    return;
  }

  if (userStore.vip.flag === 2) { // 会员过期
    vipType.value = 6;
    showVip.value = true;
    return;
  }

  if ([0, 3].includes(userStore.vip.flag)) { // 会员未生效
    uni.$u.toast(userStore.vip.flag === 0 ? 'VIP未开通！' : 'VIP未生效！');
    return;
  }

  if (!isTrustClass.value) {
    uni.$u.toast('暂无学习内容！');
    return;
  }

  uni.navigateTo({
    url: '/pages/views/wsClassroom/index',
  });
};

// 签到成功
const showSuccess = ref<boolean>(false);
const signNumber = ref<string>('');
const signInfo = ref<string>('');
// 签到
const handleSign = () => {
  showSign.value = false;
  uni.showLoading();
  doSign({ type: '1' }).then((res: DoSignResult) => {
    signNumber.value = res.lastSignIntegral ? `${res.todayIntegral - res.lastSignIntegral}+${res.lastSignIntegral}` : res.todayIntegral.toString();
    signInfo.value = res.lastDays > 0 ? `已连续签到${res.lastDays}天，明天签到可额外获得5星币` : '';
    uni.hideLoading();
    showSuccess.value = true;
    userStore.setSignStatus('1');
    signStatus.value = '1';
  });
};

// 去登录
const toLogin = () => {
  uni.navigateTo({
    url: '/pages/views/login/index',
  });
};

const getOverflow = computed(() => {
  return showSign.value || showSuccess.value || showTeacher.value || showLogin.value || showVip.value || showChangeUser.value ? 'hidden' : 'auto';
});

const totalNavigationHeight = ref<number>(0); // 导航栏总高度
const statusBarHeight = ref<number>(40); // 状态栏的高度
const navigatorHeight = ref<number>(40); // 导航栏高度
onLoad(() => {
  uni.getSystemInfo({
    success: (res: any) => {
      statusBarHeight.value = res.statusBarHeight || 40;
    },
  });

  const menu: any = uni.getMenuButtonBoundingClientRect();
  // 导航栏高度= （胶囊顶部距离-状态栏高度） x 2 + 胶囊的高度
  const navigatorH = (menu.top - statusBarHeight.value) * 2 + menu.height;
  navigatorHeight.value = navigatorH <= 30 ? 40 : navigatorH;

  // 总高度 = 状态栏的高度 + 导航栏高度
  totalNavigationHeight.value = navigatorHeight.value + statusBarHeight.value;
  setNavigationHeight(totalNavigationHeight.value.toString());

  if (!loginFlag.value && entryType === 'scan') {
    uni.$u.toast('请先登录！');
    toLogin();
  }
});

// 分享
uni.showShareMenu({
  withShareTicket: true,
  menus: ['shareAppMessage', 'shareTimeline'],
});
onShareAppMessage(() => {
  return {
    title: userStore.share_txt,
    imageUrl: userStore.share_pic_url,
  };
});
</script>

<style lang="scss" scoped>
.home {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
  background: #fff;

  .home-main {
    width: 100%;
    height: 100%;
    overflow: auto;
  }

  .home-user {
    width: 100%;
    display: flex;
    align-items: center;
    padding: 0 30rpx;
    margin-bottom: 12rpx;

    .info-name {
      font-size: 36rpx;
      color: #3D3D3D;
      font-weight: bold;
    }

    .icon-down {
      margin-left: 6rpx;
      width: 46rpx;
      height: 46rpx;
    }
  }

  .home-swiper {
    position: relative;
    width: 100%;
    height: 422rpx;
    overflow: hidden;

    .swiper {
      height: 100%;
    }

    .swiper-item {
      width: 750rpx;
      height: 422rpx;
    }
  }

  .home-ghost {
    padding: 24rpx 60rpx 0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    background: #fff;
    border-radius: 40rpx;
    position: relative;
    top: -30rpx;

    .ghost-item {
      display: flex;
      flex-direction: column;
      align-items: center;

      .ghost-img {
        width: 138rpx;
        height: 138rpx;
      }

      .ghost-text {
        font-size: 29rpx;
        color: #3D3D3D;
        line-height: 40rpx;
      }
    }
  }

  .home-signIn {
    width: 750rpx;
    height: 124rpx;
    margin-bottom: 48rpx;
  }

  .home-course {
    display: flex;
    justify-content: space-between;
    padding: 0 30rpx 28rpx;

    .course-item {
      position: relative;
      width: 341rpx;
      height: 378rpx;
      padding: 32rpx 40rpx 52rpx 42rpx;

      .item-bg {
        position: absolute;
        top: 0;
        left: 0;
        width: 341rpx;
        height: 378rpx;
      }

      .item-title {
        position: relative;
        font-weight: bold;
        font-size: 32rpx;
        color: #251504;
        line-height: 48rpx;
      }

      .item-desc {
        position: relative;
        padding: 6rpx 0 18rpx 0;
        font-size: 24rpx;
        color: #87837B;
        line-height: 36rpx;
      }

      .item-icon {
        position: relative;
        width: 150rpx;
        height: 150rpx;
        position: absolute;
        left: 42rpx;
        bottom: 52rpx;
      }

      .item-icon-right {
        right: 42rpx;
        left: auto;
      }
    }
  }

  .home-read {
    padding: 0 30rpx 40rpx;

    .read-title {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding-bottom: 30rpx;

      .title-text {
        font-size: 35rpx;
        color: #251504;
        line-height: 50rpx;
      }

      .title-more {
        display: flex;
        align-items: center;

        .more-text {
          font-size: 27rpx;
          color: #888888;
          line-height: 38rpx;
        }

        .more-icon {
          width: 15rpx;
          height: 20rpx;
          margin-left: 5rpx;
        }
      }
    }

    .read-list {
      .content {
        padding-bottom: 20rpx;
      }
    }

    .no-data {
      position: relative;
      width: 100%;
      padding-top: 44rpx;
      border-radius: 20rpx;
      display: flex;
      flex-direction: column;
      align-items: center;

      .no-data-img {
        width: 198rpx;
        height: 219rpx;
        margin-bottom: 35rpx;
      }

      .no-data-btn {
        width: 606rpx;
        margin-bottom: 96rpx;
        font-size: 35rpx;
        color: #fff;
        font-weight: bold;
        line-height: 92rpx;
        text-align: center;
        background: linear-gradient( 270deg, #FFBF13 0%, #F7C96C 98%);
        border-radius: 46rpx;
      }

      .no-data-text {
        padding: 0 50rpx 50rpx;
        font-size: 27rpx;
        color: #ACACAC;
        line-height: 38rpx;
        text-align: center;
      }

      .no-data-text-login {
        padding-top: 50rpx;
      }
    }
  }
}

:deep(.u-swiper, .u-swiper__wrapper) {
  height: 422rpx !important;
}

:deep(.u-swiper__wrapper) {
  height: 422rpx !important;
}

:deep(.u-swiper__wrapper__item__wrapper__image) {
  height: 422rpx !important;
}

:deep(.uicon-arrow-right) {
  color: #888 !important;
}

:deep(.u-line-progress__line) {
  background: rgba(74, 170, 248, 0.6) !important;
}
</style>
